package middleware

import (
	"encoding/json"
	"strings"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"

	"demo0606/modules"
)

type Users struct{}
type MyClaims struct {
	Username string
	jwt.StandardClaims
}

var jwtKey = []byte("123456")

func AuthMiddleware(c *gin.Context) {
	path := c.Request.URL.String()
	host := strings.Split(path, "?")[0]
	session := sessions.Default(c)
	userInfo := session.Get("userInfo")
	userInfoStr, ok := userInfo.(string)
	userList := []modules.User{}
	//|| host == "/apis/deletePic" || host == "/apis/uploadPic"
	if host == "/apis/dologin" {
		c.Next()
	} else {
		if ok {
			json.Unmarshal([]byte(userInfoStr), &userList)
			if userInfoStr != "" {
				c.Next()
			} else {
				c.Abort()
				c.JSON(401, gin.H{
					"message": "用户未登录",
				})
			}

		} else {
			c.Abort()
			c.JSON(401, gin.H{
				"message": "用户未登录",
			})
		}
	}

}

func YanJWT(c *gin.Context) {
	tokenData := c.Request.Header.Get("Authorization")
	tokenStr := strings.Split(tokenData, " ")[1]
	token, _, err := ParseToken(tokenStr)
	if err != nil || !token.Valid {
		c.JSON(400, gin.H{
			"message": "token传入错误",
			"success": false,
		})
		return
	} else {
		// c.JSON(200, gin.H{
		// 	"message": "验证token成功",
		// 	"Uid":     myCliant.Username,
		// 	"success": true,
		// })
		c.Next()
	}
}

func ParseToken(tokenStr string) (*jwt.Token, *MyClaims, error) {
	myClaims := &MyClaims{}
	token, err := jwt.ParseWithClaims(tokenStr, myClaims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtKey, nil
	})
	return token, myClaims, err
}
